package kz.kstu.scantest.business.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author Filipp_Stankevich
 *         created: 28.09.11 18:00
 */
public class DigestUtil {
    /**
     * MD5 digest algorithm.
     */
    public static final String ALGORITHM_MD5 = "MD5";
    /**
     * SHA digest algorithm.
     */
    public static final String ALGORITHM_SHA = "SHA";

    /**
     * Private constructor for this utility class.
     */
    private DigestUtil() {
    }

    /**
     * Completes the hash computation of the input array of bytes.
     *
     * @param message   Array of bytes for hash.
     * @param algorithm The standard name of the digest algorithm.
     * @return String representation of the resulting hash value.
     * @throws java.security.NoSuchAlgorithmException
     *          If the algorithm is not available in the caller's environment.
     */
    public static String digest(byte[] message, String algorithm) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance(algorithm);
        md.reset();
        byte[] digest = md.digest(message);
        StringBuilder buffer = new StringBuilder();
        for (byte element : digest) {
            buffer.append(String.format("%02x", element));
        }
        return buffer.toString();
    }

    /**
     * Completes the hash computation of the input string.
     *
     * @param message   String for hash.
     * @param algorithm The standard name of the digest algorithm.
     * @return String representation of the resulting hash value.
     * @throws NoSuchAlgorithmException If the algorithm is not available in the caller's environment.
     */
    public static String digest(String message, String algorithm) throws NoSuchAlgorithmException {
        return digest(message.getBytes(), algorithm);
    }
}
